package kr.co.boogui.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.boogui.actions.ActionHandler;

@WebServlet({"/index.html", "*.bi"})
public class MVCController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void mvcProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		// 요청 URL 분석
		String uri = req.getRequestURI();
		String cmd = uri.substring(uri.lastIndexOf("/"));
		
		// 요청 URL에 따른 action 클래스 불러오기
		ActionHandler action = (ActionHandler)MVCControllerSetup.getActionsMap().get(cmd);
		
		// 불러온 action 클래스를 실행하고 결과를 출력할 viewPage를 받음
		String viewPage = action.execute(req, res);
		// viewPage를 forward할지 redirect할지 결정
		String dispatcher[] = viewPage.split("[|]");
		
		// viewPage 처리유형이
		if (dispatcher[0].equals("f")) {	// forward라면
			RequestDispatcher rd = req.getRequestDispatcher(dispatcher[1]);
			rd.forward(req, res);
		} else if (dispatcher[0].equals("r")) {	// redirect라면
			res.sendRedirect(dispatcher[1]);
		}
		
	}
       
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		mvcProcess(req, res);
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		mvcProcess(req, res);
	}

}
